// (c) 2015 Teresa Holfeld
package com.holfeld.teresa.vocabtrainer;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.holfeld.teresa.vocabtrainer.provider.VocablePair;
import com.holfeld.teresa.vocabtrainer.provider.Vocabulary;
import com.holfeld.teresa.vocabtrainer.provider.VocabularyPool;

/**
 * A fragment representing a single Stack detail screen.
 * This fragment is either contained in a {@link VocabularyListActivity}
 * in two-pane mode (on tablets) or a {@link TrainVocabularyActivity}
 * on handsets.
 *
 * @author Teresa Holfeld, teresa.holfeld@gmail.com
 */
public class TrainVocabularyFragment extends Fragment {

    /**
     * The fragment argument representing the vocabulary that this fragment represents.
     */
    public static final String ARG_VOCAB_NAME = "vocab_name";

    /**
     * The VocabularyPool holds the current train stack.
     */
    private VocabularyPool mVocabularyPool;

    /**
     * The vocabulary (stack) that this fragment represents.
     */
    private Vocabulary mVocabulary;

    /**
     * The currently displayed vocable.
     */
    private VocablePair mActiveVocable;

    /**
     * The direction: true = show locale 1, guess locale 2
     */
    private boolean mL1ToL2 = true;

    // layout elements
    private TextView mLocales;
    private TextView mFlashcardFrontside;
    private TextView mFlashcardBackside;
    private TextView mProgressView;
    private LinearLayout mRightWrong;
    private Button mRightButton;
    private Button mWrongButton;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public TrainVocabularyFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments().containsKey(ARG_VOCAB_NAME)) {
            String vocabularyName = getArguments().getString(ARG_VOCAB_NAME);
            mVocabularyPool = VocabularyPool.getInstance(getActivity());
            mVocabulary = mVocabularyPool.getVocabulary(vocabularyName);
            mVocabularyPool.setActiveVocabulary(vocabularyName);
        }
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        getActivity().setTitle(mVocabulary.getName());
        View rootView = inflater.inflate(R.layout.fragment_train_vocabulary, container, false);

        mFlashcardFrontside = (TextView) rootView.findViewById(R.id.flashcardFrontside);
        mFlashcardBackside = (TextView) rootView.findViewById(R.id.flashcardBackside);
        mProgressView = (TextView) rootView.findViewById(R.id.progress);
        mRightWrong = (LinearLayout) rootView.findViewById(R.id.rightWrong);
        mLocales = (TextView) rootView.findViewById(R.id.vocabularyInfo);
        mRightButton = (Button) rootView.findViewById(R.id.right);
        mWrongButton = (Button) rootView.findViewById(R.id.wrong);

        setFlashcardTexts();
        setLocalesText();
        setProgressText();
        setButtonListeners();
        veilFlashCard();

        return rootView;
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_train_vocabulary_fragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.change_direction_item:
            mL1ToL2 = !mL1ToL2;
            mVocabularyPool.refillTrainingSet();
            setFlashcardTexts();
            setLocalesText();
            setProgressText();
            veilFlashCard();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    private void setFlashcardTexts() {
        // TODO case with 0 items in the vocabulary
        mActiveVocable = mVocabularyPool.getRandomVocable();
        if (mActiveVocable == null) {
            askForAnotherRound();
        } else if (mL1ToL2) {
            mFlashcardFrontside.setText(mActiveVocable.getVocable1());
            mFlashcardBackside.setText(mActiveVocable.getVocable2());
        } else {
            mFlashcardFrontside.setText(mActiveVocable.getVocable2());
            mFlashcardBackside.setText(mActiveVocable.getVocable1());
        }
    }

    private void setLocalesText() {
        String locale1 = mVocabulary.getLocale1();
        String locale2 = mVocabulary.getLocale2();
        if (mL1ToL2) {
            mLocales.setText(locale1 + " - " + locale2);
        } else {
            mLocales.setText(locale2 + " - " + locale1);
        }
    }

    private void setProgressText() {
        int total = mVocabularyPool.getTotal();
        int progress = mVocabularyPool.getProgress();
        mProgressView.setText(String.valueOf(progress) + " / " + String.valueOf(total));
    }

    private void setButtonListeners() {
        mFlashcardFrontside.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unveilFlashCard();
            }
        });
        mRightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mVocabularyPool.wasRight(mActiveVocable)) {
                    setFlashcardTexts();
                    setProgressText();
                    veilFlashCard();
                } else {
                    askForAnotherRound();
                }
            }
        });
        mWrongButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mVocabularyPool.wasWrong(mActiveVocable);
                setFlashcardTexts();
                veilFlashCard();
            }
        });
    }

    private void veilFlashCard() {
        mFlashcardFrontside.setClickable(true);
        mFlashcardBackside.setVisibility(View.INVISIBLE);
        mRightWrong.setVisibility(View.INVISIBLE);
    }

    private void unveilFlashCard() {
        mFlashcardFrontside.setClickable(false);
        mFlashcardBackside.setVisibility(View.VISIBLE);
        mRightWrong.setVisibility(View.VISIBLE);
    }

    private void askForAnotherRound() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setMessage(getResources().getString(R.string.you_got_everything_right))
                .setCancelable(false)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mVocabularyPool.refillTrainingSet();
                        setFlashcardTexts();
                        setProgressText();
                        veilFlashCard();
                        dialog.cancel();
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        mVocabularyPool.refillTrainingSet();
                        setFlashcardTexts();
                        setProgressText();
                        veilFlashCard();
                        NavUtils.navigateUpTo(getActivity(),
                                new Intent(getActivity(), VocabularyListActivity.class));
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
}
